package deng.java.examples;

// See http://www.redhat.com/docs/manuals/jboss/jboss-eap-4.2/doc/Server_Configuration_Guide/Using_JMX_as_a_Microkernel-Writing_JBoss_MBean_Services.html
// Needs META-INF/jboss-service.xml to deploy.
//
// The JNDIMap MBean implementation - Create a HashMap object and bind it to the JNDI naming server.
// We only using JBoss specific class here because we are dealing with it's naming server. This class
// can be non-JBoss sepecific.
//
import java.util.HashMap;
import javax.naming.InitialContext;
import javax.naming.Name;
import javax.naming.NamingException;
import org.jboss.naming.NonSerializableFactory;
import org.apache.log4j.Logger;

public class JNDIMap implements JNDIMapMBean
{
	private static Logger logger = Logger.getLogger(JNDIMap.class);
	
    private String jndiName;
    private HashMap contextMap = new HashMap();
    private boolean started;
    
    public String getJndiName()
    {
        return jndiName;
    }
    public void setJndiName(String jndiName) throws NamingException
    {
        String oldName = this.jndiName;
		logger.trace("Old jndiName=" + oldName);
        this.jndiName = jndiName;
        if (started) {
            unbind(oldName);
            try {
                rebind();
            } catch(Exception e) {
                NamingException ne = new NamingException("Failedto update jndiName=" + jndiName);
                ne.setRootCause(e);
                throw ne;
            }
        }
    }

    public void start() throws Exception
    {
		logger.trace("Starting service.");
        started = true;
        rebind();
		logger.debug("Service is ready");
    }
                
    public void stop()
    {
		logger.trace("Stopping service.");
        started = false;
        unbind(jndiName);
		logger.debug("Service destroyed.");
    }
                
    private void rebind() throws NamingException
    {
        InitialContext rootCtx = new InitialContext();
        Name fullName = rootCtx.getNameParser("").parse(jndiName);
        logger.info("Rebind: fullName="+fullName);
        NonSerializableFactory.rebind(fullName, contextMap, true);
    }

    private void unbind(String jndiName)
    {
        try {
			logger.info("Unbind: jndiName="+jndiName);
            InitialContext rootCtx = new InitialContext();
            rootCtx.unbind(jndiName);
            NonSerializableFactory.unbind(jndiName);
        } catch(NamingException e) {
            logger.error("Failed to unbind " + jndiName, e);
        }
    }
}

